package cn.iocoder.yudao.module.project.controller.admin.dispatchlist;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.iocoder.yudao.framework.common.exception.ServiceException;
import cn.iocoder.yudao.module.project.config.projectDefine;
import cn.iocoder.yudao.module.project.dal.dataobject.kismaterielexwarehouse.KisMaterielExWarehouseDO;
import cn.iocoder.yudao.module.project.dal.dataobject.order.OrderDO;
import cn.iocoder.yudao.module.project.dal.dataobject.orderdetail.OrderDetailDO;
import cn.iocoder.yudao.module.project.dal.mysql.kismaterielexwarehouse.KisMaterielExWarehouseMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.apache.poi.ss.usermodel.Sheet;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import javax.validation.constraints.*;
import javax.validation.*;
import javax.servlet.http.*;
import java.util.*;
import java.io.IOException;
import java.util.stream.Collectors;

import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.error;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;

import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.*;
import static cn.iocoder.yudao.module.project.config.projectDefine.HTTP_STATUS.ERROR_STATUS;
import static cn.iocoder.yudao.module.project.config.projectDefine.MATERIAL_STATUS.MATERIAL_STATUS_0;
import static cn.iocoder.yudao.module.project.config.projectDefine.ORDER_TYPE.ORDER_TYPE_1;
import static cn.iocoder.yudao.module.project.config.projectDefine.ORDER_TYPE.ORDER_TYPE_2;
import static cn.iocoder.yudao.module.project.config.projectDefine.SUBMIT_STATUS.SUBMIT_STATUS_0;

import cn.iocoder.yudao.module.project.controller.admin.dispatchlist.vo.*;
import cn.iocoder.yudao.module.project.dal.dataobject.dispatchlist.DispatchListDO;
import cn.iocoder.yudao.module.project.service.dispatchlist.DispatchListService;
import org.springframework.web.multipart.MultipartFile;

@Tag(name = "管理后台 - 派工单")
@RestController
@RequestMapping("/project/dispatch-list")
@Validated
public class DispatchListController {

    @Resource
    private DispatchListService dispatchListService;

    @Resource
    private KisMaterielExWarehouseMapper kisMaterielExWarehouseMapper;

    @PostMapping("/create")
    @Operation(summary = "创建派工单")
    @PreAuthorize("@ss.hasPermission('project:dispatch-list:create')")
    public CommonResult<Integer> createDispatchList(@Valid @RequestBody DispatchListSaveReqVO createReqVO) {
        return success(dispatchListService.createDispatchList(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新派工单")
    @PreAuthorize("@ss.hasPermission('project:dispatch-list:update')")
    public CommonResult<Boolean> updateDispatchList(@Valid @RequestBody DispatchListSaveReqVO updateReqVO) {
        dispatchListService.updateDispatchList(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除派工单")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('project:dispatch-list:delete')")
    public CommonResult<Boolean> deleteDispatchList(@RequestParam("id") Integer id) {
        dispatchListService.deleteDispatchList(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得派工单")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('project:dispatch-list:query')")
    public CommonResult<DispatchListRespVO> getDispatchList(@RequestParam("id") Integer id) {
        DispatchListDO dispatchList = dispatchListService.getDispatchList(id);
        return success(BeanUtils.toBean(dispatchList, DispatchListRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得派工单分页")
    @PreAuthorize("@ss.hasPermission('project:dispatch-list:query')")
    public CommonResult<PageResult<DispatchListRespVO>> getDispatchListPage(@Valid DispatchListPageReqVO pageReqVO) {
        PageResult<DispatchListDO> pageResult = dispatchListService.getDispatchListPage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, DispatchListRespVO.class));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出派工单 Excel")
    @PreAuthorize("@ss.hasPermission('project:dispatch-list:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportDispatchListExcel(@Valid DispatchListPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<DispatchListDO> list = dispatchListService.getDispatchListPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "派工单.xls", "数据", DispatchListRespVO.class,
                        BeanUtils.toBean(list, DispatchListRespVO.class));
    }


    @PostMapping("/importExcel")
    @Operation(summary = "导入派工单 Excel")
    public CommonResult<String> importExcel(@RequestParam("file") MultipartFile file) {
        try{
            return dispatchListService.importExcel(file.getInputStream());
        }catch (Exception e){
            throw new ServiceException(ERROR_STATUS,e.getMessage());
        }
    }

    @GetMapping("/getDispatchList")
    @Operation(summary = "获得派工单列表")
    public CommonResult<List<DispatchListRespVO>> getDispatchList(@Valid DispatchListPageReqVO pageReqVO) {
        List<DispatchListRespVO> respVOList = null;

        QueryWrapper<KisMaterielExWarehouseDO> kisMaterielExWarehouseDOQueryWrapper = new QueryWrapper<>();
        kisMaterielExWarehouseDOQueryWrapper.eq("order_code", pageReqVO.getTicketNumber());
        kisMaterielExWarehouseDOQueryWrapper.eq("submit_status", SUBMIT_STATUS_0);
        kisMaterielExWarehouseDOQueryWrapper.eq("material_status", MATERIAL_STATUS_0);
        List<KisMaterielExWarehouseDO> kisMaterielExWarehouseDOList = kisMaterielExWarehouseMapper.selectList(kisMaterielExWarehouseDOQueryWrapper);
        if(null != kisMaterielExWarehouseDOList && kisMaterielExWarehouseDOList.size() > 0){
            respVOList = new ArrayList<>();
            for(KisMaterielExWarehouseDO kisMaterielExWarehouseDO : kisMaterielExWarehouseDOList){
                DispatchListRespVO dispatchListRespVO = new DispatchListRespVO();
                dispatchListRespVO.setModelKp(kisMaterielExWarehouseDO.getType());
                dispatchListRespVO.setTicketNumber(kisMaterielExWarehouseDO.getOrderCode());
                respVOList.add(dispatchListRespVO);
            }
        }else{
            pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
            PageResult<DispatchListDO> pageResult = dispatchListService.getDispatchListPage(pageReqVO);
            List<DispatchListDO> list = pageResult.getList();
            respVOList = BeanUtils.toBean(list, DispatchListRespVO.class);

            for (DispatchListRespVO dispatchListRespVO : respVOList){
                String modelKp = dispatchListRespVO.getModelKp();
                dispatchListRespVO.setModelKp(modelKp);
            }
        }

        return success(respVOList);
    }

}
